var gson = (function () {
	__gson__ = function () {
		this.version = 0.1;
		this.loaded = new Array();
		this.waitIntv = null;
		this.timeout = 10000;
		this.packages = {};
	};
	
	/**
	 * 获取项目跟路径
	 *
	 * @returns
	 */
	__gson__.prototype.rootPath = function () {
		var curWwwPath = window.document.location.href;
		var pathName = window.document.location.pathname;
		var pos = curWwwPath.indexOf(pathName);
		var localhostPaht = curWwwPath.substring(0, pos);
		var projectName = pathName.substring(0,
				pathName.substr(1).indexOf('/') + 1);
		return (localhostPaht + projectName);
	};
	
	/**
	 * 日志输出
	 * @param msg
	 */
	__gson__.prototype.log = function (msg) {
		if (window.console && window.console.log) {
			console.log(msg);
		} else {
			var log = document.getElementById("_godson_log_");
			if (!log) {
				log = document.createElement('div');
				log.id = "_godson_log_";
				log.style.width = "97%";
				log.style.height = "20%";
				log.style.fontSize = "12px";
				log.style.border = "1px blue solid";
				log.style.padding = "5px";
				log.style.margin = "5px 0";
				log.style.overflow = "auto";
				log.style.position = "absolute";
				log.style.bottom = "0";
				document.body.appendChild(log);
				var close = document.createElement('div');
				close.innerHTML = "X";
				close.style.padding = "3px 5px";
				close.style.position = "absolute";
				close.style.top = "0";
				close.style.right = "0";
				close.style.background = "blue";
				close.style.color = "white";
				close.style.fontWeight = "bold";
				close.style.cursor = "pointer";
				close.onclick = function () {
					document.body.removeChild(log);
				};
				log.appendChild(close);
			}
			var info = document.createElement('div');
			info.innerHTML = this.format(new Date(), "yyyy-MM-dd hh:mm:ss S") + " logInfo：" + msg;
			log.appendChild(info);
		}
	};
	
	/**
	 * 定义包名
	 * 		eg:
	 * 			注册命名空间：gson.package("com.js.gson");
	 * 			使用：com.js.gson.function = function(){}
	 * 			      com.js.gson.function2 = function(){}
	 */
	__gson__.prototype.package = function () {
		var a = arguments,
		o = null,
		i,
		j,
		d,
		rt;
		for (i = 0; i < a.length; ++i) {
			d = a[i].split(".");
			rt = d[0];
			eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
			for (j = 1; j < d.length; ++j) {
				o[d[j]] = o[d[j]] || {};
				o = o[d[j]];
			}
		}
		return o;
	};
	
	/**
	 * 字符串模版替换
	 *
	 * @param str
	 *            需要替换的字符串，例如：我是{{key1}}替换的字符串{{key2}}。
	 * @param data
	 *            替换的数据。json格式的数据或者数组。
	 *            eg：
	 *				str：我是{{key1}}替换的字符串{{key2}}。
	 *              data：{key1:"替换",key2:"替换2"}
	 *
	 * 			    str：我是{{0}}替换的字符串{{1}}。
	 * 			    data：["替换","替换2"]
	 * @returns
	 */
	__gson__.prototype.replaceAll = function (str, data) {
		for (var key in data) {
			var value = data[key];
			if (value == null)
				value = "&nbsp;";
			str = str.replace(new RegExp("{{" + key + "}}", "gm"), value);
		}
		return str;
	};
	
	/**
	 * 获取链接参数
	 * @param param
	 * 		需要获取的参数。如果不传，则返回所有参数的json对象
	 * @param href
	 * 		指定链接获取参数
	 * @returns
	 */
	__gson__.prototype.URLParams = function (param, href) {
		var params = {};
		
		href = href || window.location.toString();
		
		var uri = href.split("?");
		
		if (!uri[1])
			return null;
		
		uri = uri[1].split("#")[0];
		
		var paramSet = uri.split("&");
		var temp = [];
		for (index in paramSet) {
			temp = paramSet[index].split("=");
			params[temp[0]] = temp[1];
		}
		
		if (param) {
			if (params[param])
				return params[param];
			else
				return null;
		} else {
			return params;
		}
	};
	
	/**
	 * 字符串处理。去除前后空格
	 * @param str
	 * 		需要处理的字符串
	 * @returns
	 */
	__gson__.prototype.trim = function (str) {
		return str.replace(/^\s*/, "").replace(/\s*$/, "");
	};
	
	/**
	 * 数组操作函数。去除数组中重复元素
	 * @param array
	 * 		待处理的数据元素
	 * @returns
	 */
	__gson__.prototype.unique = function (array) {
		var i,
		tmp = {};
		for (i = 0; i < array.length; i++) {
			if (typeof(tmp[array[i]]) == "undefined")
				tmp[array[i]] = 1;
		}
		array.length = 0;
		for (i in tmp)
			array[array.length] = i;
		return array;
	};
	
	/**
	 * 数组操作函数。判断元素是否存在于数组中
	 * @param array
	 * 		目标数组
	 * @param value
	 * 		判断值
	 * @returns {Number}
	 * 		如果存在返回元素下标，不存在返回-1
	 */
	__gson__.prototype.contains = function (array, value) {
		for (var i = 0; i < array.length; i++) {
			if (array[i] == value) {
				return i;
			}
		}
		return -1;
	};
	
	/**
	 * 格式化时间
	 * @param date
	 * @param format
	 * @returns
	 */
	__gson__.prototype.format = function (date, format) {
		if (!format) {
			format = "yyyy-MM-dd hh:mm:ss";
		}
		
		var o = {
			"M+" : date.getMonth() + 1, // month
			"d+" : date.getDate(), // day
			"h+" : date.getHours(), // hour
			"m+" : date.getMinutes(), // minute
			"s+" : date.getSeconds(), // second
			"q+" : Math.floor((date.getMonth() + 3) / 3), // quarter
			"S" : date.getMilliseconds() // millisecond
		};
		
		if (/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
			}
		}
		return format;
	};
	
	/**
	 * 根据包名加载js
	 * @param arguments
	 * 	eg:
	 * 		gson.load('com.gson.user','com.gson.role');
	 *      or
	 *      gson.load('com.gson.user','com.gson.role',function(){});
	 * @returns {__gson__}
	 */
	__gson__.prototype.load = function () {
		var args = arguments,
		i = 0,
		nss = new Array(),
		cbs = new Array(),
		loaded = new Array(),
		_g = this;
		
		for (i; i < args.length; i++) {
			var ns = args[i];
			if (typeof ns === "string") {
				nss.push(ns);
			} else if (typeof ns === "function") {
				cbs.push(ns);
			}
		}
		
		i = 0;
		for (i; i < nss.length; i++) {
			if (_g.contains(_g.loaded, nss[i]) == -1) {
				loadJs(_g.rootPath() + _g.packages[nss[i]] + "?p=" + nss[i], function () {
					var pk = _g.URLParams("p", this.src);
					_g.loaded.push(pk);
					loaded.push(eval(pk));
				});
			} else {
				loaded.push(eval(nss[i]));
			}
		}
		
		var timeout = 0;
		_g.waitIntv = setInterval(function () {
				if (nss.length == loaded.length) {
					//执行回调
					for (var i = 0; i < cbs.length; i++) {
						if (loaded.length > 1) {
							cbs[i].apply(this, loaded);
						} else {
							cbs[i].call(loaded[0]);
						}
					}
					
					//执行main函数
					for (var i = 0; i < loaded.length; i++) {
						if (loaded[i].main) {
							loaded[i].main();
						}
					}
					//还原设置
					clearInterval(_g.waitIntv);
					_g.waitIntv = loaded = nss = cbs = null;
				}
				
				//超时处理
				timeout += 100;
				if (timeout == _g.timeout) {
					clearInterval(_g.waitIntv);
					_g.waitIntv = loaded = nss = cbs = null;
					alert("js加载超时！");
				}
			}, 100);
		
		return this;
		
		/**
		 * js 加载
		 * @param url
		 * 		路径
		 * @param callback
		 */
		function loadJs(url, callback) {
			var done = false;
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.language = 'javascript';
			script.src = url + "&v=" + _g.version;
			script.onload = script.onreadystatechange = function () {
				if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')) {
					done = true;
					script.onload = script.onreadystatechange = null;
					if (callback) {
						callback.call(script);
					}
				}
			};
			document.getElementsByTagName("head")[0].appendChild(script);
		}
	};
	
	return new __gson__();
})();
